package com.example.demo.service.impl;

import com.example.demo.Util.Result;
import com.example.demo.Util.ResultUtil;
import com.example.demo.mapper.StudentMap;
import com.example.demo.mapper.TeacherMap;
import com.example.demo.mapper.UserMap;
import com.example.demo.po.College;
import com.example.demo.po.Student;
import com.example.demo.po.Teacher;
import com.example.demo.po.User;
import com.example.demo.po.dto.TeacherParam;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImp implements UserService {

    @Autowired
    UserMap userMap;

    @Autowired
    TeacherMap teacherMap;

    @Autowired
    StudentMap studentMap;

    @Override
    public User getUserByLogin(String username,String password) {

        if(userMap.getUserByLogin(username).size() == 0){
            return null;
        }
        User user = userMap.getUserByLogin(username).get(0);
        if(user.getPassword().equals(password)){
          return user;
        }

        return null;
    }

    @Override
    public Result RegistryUser(User user) {

      if( userMap.getUserByLogin(user.getUsername()).size() > 0 ){
          return  ResultUtil.success("用户名重名");
      }


        int userid=  userMap.SaveUser(user);

        if(user.getRole().equals("teacher")){
             TeacherParam teacher = new TeacherParam();
             teacher.setName(user.getNickname());
             teacher.setUserid(user.getId());
             teacherMap.SaveTeacher(teacher);

        }else if(user.getRole().equals("student")){
            Student student = new Student();
            student.setName(user.getNickname());
            student.setUserid(user.getId());
            studentMap.SaveStudent(student);
        }


        return ResultUtil.success("注册成功") ;
    }

    @Override
    public Result UpdateUser(User user) {


        if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())||StringUtils.isEmpty(user.getNickname()))
        {
            return ResultUtil.fail("名称、用户名、密码必填");
        }

        userMap.UpdateUser(user);

        return ResultUtil.success(user);
    }
}
